import React, { Component } from 'react';
import { Button, Form, Select, Card, Input, message } from 'antd';
import { connect } from 'dva';
import style from '../formConfig.less';
import { transferOption } from '@/support/utils';
import router from 'umi/router';
import FunctionTree from './functionTree';

const { TextArea } = Input;

const mapStateToProps = (state: any) => {
  return {
    // list:state.basicCommands
  };
};

export enum FeatureConfigEnum {
  App = 1,
  CarMachine = 2,
  Algorithm = 3,
  VehicleHealth = 4,
}

export const featureConfOptions = [
  {
    label: 'APP功能',
    value: FeatureConfigEnum.App,
  },
  {
    label: '车机功能',
    value: FeatureConfigEnum.CarMachine,
  },
  {
    label: '算法',
    value: FeatureConfigEnum.Algorithm,
  },
  {
    label: '车辆健康',
    value: FeatureConfigEnum.VehicleHealth,
  },
];

class FormConfig extends Component<any, any> {
  treeRef: { current: null | any };

  constructor(props: any) {
    super(props);
    this.treeRef = React.createRef();
  }
  state = {
    treeListObj: {},
    postLoading: false,
    treeKeyList: {},
    SeriesCodeList: [],
    GroupList: [],
    halfCheckedList: {},
    brandOptions: [],
    brandId: '',
    isEdit: false,
    nodeData: {},
    checkedData: {},
  };

  formRef = React.createRef();
  componentDidMount() {
    const { location } = this.props;
    const { id, seriesCode, brandId } = location?.query;
    //编辑
    if (seriesCode) {
      this.getTreeAll(seriesCode);
    }
    if (id) {
      this.getInfo(id);
    }
    //获取品牌信息
    this.getBrandList();
    // 车系列表
    this.getSeriesCodeList(brandId);
  }
  getBrandList = () => {
    const { dispatch, location } = this.props;
    //获取品牌数据
    dispatch({
      type: 'basedata/brandFetch',
      callback: (res: any) => {
        this.setState(
          {
            brandOptions: res?.data,
          },
          () => {
            this.formRef.current?.setFieldsValue({
              brandId: location?.query.brandId,
            });
          },
        );
      },
    });
  };
  //获取配置项所有信息及数据处理
  getFunctionInfo = (seriesCode: string) => {
    const { location } = this.props;
    const { id } = location?.query;
    this.getTreeAll(seriesCode);
    if (id) {
      this.getInfo(id);
    }
  };
  getTreeAll = (seriesCode: string) => {
    const { dispatch } = this.props;
    return new Promise(resolve => {
      dispatch({
        type: 'formConfig/getData',
        payload: { url: `/remote/config/base/feature/item/list/all`, seriesCode },
        callback: res => {
          const { data } = res;
          let initNodeData = {};
          featureConfOptions.forEach(item => {
            let { value } = item;
            initNodeData[value] = data[value] || [];
          });
          this.setState({
            nodeData: initNodeData,
          });
          resolve(initNodeData);
        },
      });
    });
  };

  // 车系列表
  getSeriesCodeList = (brandId: string) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'formConfig/getDataWithRes',
      payload: { url: '/msdevice/base/vehicle/series/bybrand/list', brandId },
      callback: res => {
        this.setState({
          SeriesCodeList: res?.data || [],
        });
      },
    });
  };
  // 车型组
  getGroupList = seriesCode => {
    const { dispatch } = this.props;
    dispatch({
      type: 'formConfig/postDataWithRes',
      payload: { url: '/vehicle/group/findBySeriesCode', seriesCode },
      callback: res => {
        this.setState({
          GroupList: res?.data || [],
        });
      },
    });
  };

  // 获取详情
  getInfo = (sid: string) => {
    const { dispatch, location } = this.props;
    dispatch({
      type: 'formConfig/getData',
      payload: { url: '/vehicle/functionConfig/findOne', sid },
      callback: res => {
        const { data } = res;
        let { function: checkedFeatureData, remark, sid, vehicleSeries, vehicleTypeGroup } = data;
        let initCheckedData = {};
        featureConfOptions.forEach(item => {
          let { value } = item;
          let checkedFeatureConfig = checkedFeatureData.find(item => item.featureType === value);
          initCheckedData[value] =
            checkedFeatureConfig?.featureConfigs.map(item => ({ ...item, sid: item.itemDataId })) ||
            [];
        });

        this.formRef.current?.setFieldsValue({
          sid,
          vehicleSeries,
          vehicleTypeGroup,
          remark,
        });
        if (data.vehicleSeries) {
          this.getGroupList(data.vehicleSeries);
        }
        this.setState({
          checkedData: initCheckedData,
          isEdit: sid ? true : false,
        });
      },
    });
  };

  onFinish = async () => {
    let values = await this.formRef.current?.validateFields();
    let checkedNodes: any[] | boolean = await this.treeRef.current?.validateSort();
    if (!checkedNodes) {
      return;
    }
    let allCheckedData = this.treeRef.current?.getAllCheckedData() || [];
    // 选中的节点数据；
    let functionItems = (allCheckedData as any[]).map(item => {
      // isCheckAll 1:全选， 2：半选
      const { sid, isCheckAll = 2, otherName, sortNum, funcParam, tips } = item;
      return {
        itemDataId: sid,
        isCheckAll,
        otherName,
        sortNum,
        funcParam,
        tips,
      };
    });

    const { dispatch, location } = this.props;
    const sid = location?.query?.id;
    const type = sid ? 'update' : 'save';
    let { brandId, vehicleSeries, vehicleTypeGroup, remark } = values;
    let params = {
      brandId,
      vehicleSeries,
      vehicleTypeGroup,
      remark,
      functionItems,
    };

    sid && Object.assign(params, { sid });

    dispatch({
      type: 'ability/postObjWithRes',
      payload: { url: `/vehicle/functionConfig/${type}`, ...params },
      callback: res => {
        if (res.statusCode === '0') {
          // 返回
          // this.props.history.goBack();
          this.goBackFn();
          // 提示
          message.success(`${sid ? '更新' : '新增'}成功`);
        }
      },
    });
  };

  goBackFn = () => {
    this.formRef.current?.resetFields();
    this.setState({
      brandOptions: [],
      brandId: '',
    });
    router.push({
      pathname: '/remoteConfiguration/functionConfig',
      state: { sourceRouter: 'functionConfig' },
    });
    // this.props?.history?.goBack();
  };

  render() {
    const { postLoading, SeriesCodeList, GroupList, isEdit, nodeData, checkedData } = this.state;
    const seriesSelect = {
      placeholder: '请选择车系',
      options: SeriesCodeList,
      fieldNames: {
        label: 'seriesName',
        value: 'seriesCode',
      },
      onChange: (value: string) => {
        // 是否联动车型？
        this.getGroupList(value);
        this.getFunctionInfo(value); //根据车系编码获取所有功能项数据
        this.formRef.current?.setFieldsValue({
          vehicleTypeGroup: undefined,
        });
      },
      disabled: isEdit,
    };

    const modelSelect = {
      placeholder: '请选择车型组',
      fieldNames: {
        label: 'name',
        value: 'sid',
      },
      options: GroupList,
      disabled: isEdit,
    };

    return (
      <Card className={style.formConfig}>
        <Form
          labelCol={{ span: 3 }}
          wrapperCol={{ span: 15 }}
          onFinish={this.onFinish}
          className="form-box"
          ref={this.formRef}
        >
          <Form.Item
            name="brandId"
            label="品牌"
            rules={[{ required: false, message: '请选择' }]}
            initialValue={this.state.brandId}
          >
            <Select placeholder="请选择" disabled={true}>
              {transferOption(this.state.brandOptions, ['brandCode', 'brandName'])}
            </Select>
          </Form.Item>
          <Form.Item
            label="车系"
            name="vehicleSeries"
            rules={[{ required: true, message: '请选择车系' }]}
          >
            <Select {...seriesSelect}></Select>
          </Form.Item>
          <Form.Item
            label="车型组"
            name="vehicleTypeGroup"
            rules={[{ required: true, message: '请选择车型组' }]}
          >
            <Select {...modelSelect}></Select>
          </Form.Item>
          <Form.Item label="备注" name="remark">
            <TextArea rows={4} placeholder="请输入备注" />
          </Form.Item>
          <FunctionTree nodeData={nodeData} checkedData={checkedData} ref={this.treeRef} />
          <Form.Item labelCol={{ span: 0 }} wrapperCol={{ span: 24 }} className="btn-box">
            <Button type="primary" htmlType="submit" loading={postLoading} className="form-btn">
              保存
            </Button>
            <Button onClick={this.goBackFn}>取消</Button>
          </Form.Item>
        </Form>
      </Card>
    );
  }
}

export default connect(mapStateToProps)(FormConfig);
